import cloud from '@lafjs/cloud'
const db = cloud.database();
const dbm = cloud.mongo.db
import { changeStudentSource } from "@/admin/web/set_student_info";
import { setUserInfo } from "@/thirdParty/moxueyuanUtils";
import { changeOrderStatus } from "@/web/orderUtils";
import { changeOrderInfo, setOrderBaseInfo } from "@/admin/web/set_order_info";

let dbName = "web-order"
let data
let userId //当前用户id

export default async function (ctx: FunctionContext) {
  data = ctx.body.data

  if (cloud.utils.isString(ctx.user.uid)) {
    userId = ctx.user.uid
  } else {
    userId = ctx.user.uid._id
  }

  switch (ctx.body.type) {
    case "add":
      return add()
      break;
    case "update":
      return update()
      break;
    case "del":
      return delFunc()
      break;
    case "list":
      return list()
      break;
    case "details":
      return details()
      break;
    case "clearAll":
      return clearAll()
      break;
    case "intendedCustomers"://意向客户
      return intendedCustomers()
      break;
    case "intendedCustomersExport"://意向客户导出
      return intendedCustomersExport()
      break;
    case "modifyOrderAmount"://修改订单金额
      return modifyOrderAmount()
      break;
    case "editOrderMoxueyuan"://修改订单里面的魔学院信息
      return editOrderMoxueyuan()
      break;
    case "freeOrderRefund"://免费订单退款
      return freeOrderRefund()
      break;
    case "getOrderByOutTradeNo"://根据订单号查出订单信息
      return getOrderByOutTradeNo()
      break;
    default://不分页查询
      return Search()
      break;
  }
}

//根据订单号查出订单信息
async function getOrderByOutTradeNo() {
  let arr = []
  for (let index = 0; index < data.length; index++) {
    const element = data[index];
    let res = await cloud.nw.db.findByWhereJson({
      dbName,
      whereJson: { _id: element },
    });
    if (res && res._id) arr.push(res)
  }
  return cloud.utils.requestReturn({ data: arr })
}

//免费订单退款
async function freeOrderRefund() {
  let orderId = data.orderId
  delete data.orderId
  // console.log("免费订单data", data)
  // return cloud.utils.requestReturn({ data: "" })
  await cloud.nw.db.update({
    dbName,
    whereJson: { _id: orderId },
    dataJson: data
  });
  let res = await cloud.nw.db.findByWhereJson({
    dbName,
    whereJson: { _id: orderId },
  });
  changeStudentSource(res.out_trade_no); // 改变学生来源
  return cloud.utils.requestReturn({ data: "" })
}

//修改魔学院信息
async function editOrderMoxueyuan() {
  await setUserInfo(data)
  return cloud.utils.requestReturn({ data: "" })
}

//修改订单金额
async function modifyOrderAmount() {
  let { orderId, price } = data
  //订单详情
  let res = await cloud.nw.db.findByWhereJson({
    dbName, whereJson: { _id: orderId },
  });
  let dataJson = { manualPrice: 1 }  //manualPrice:手动改价的标识
  //原始的订单金额
  dataJson["originalPrice"] = res.price

  //如果有预报名的字段,也修改对应的订单金额
  if (res.hasOwnProperty("signUpPrice")) {
    let curriculumSignUpPrice = getPayAdvance(res)  //课程里设置的预付款金额
    //修改预付款
    dataJson["signUpPrice"] = Number(price)
    //修改订单金额 为 原订单金额 - 课程设置的预付款金额
    dataJson["price"] = Number(res.price) - Number(curriculumSignUpPrice)

    //原始的预付款金额
    dataJson["originalSignUpPrice"] = res.signUpPrice
  } else {
    dataJson["price"] = Number(price)
  }

  //判断订单状态 (修改金额为0，执行后续的逻辑)
  if (price == 0) dataJson["status"] = await setOrderAfterAction()

  //更新订单信息
  await cloud.nw.db.update({
    dbName,
    whereJson: { _id: orderId },
    dataJson
  });
  changeStudentSource(res.out_trade_no); // 改变学生来源
  return cloud.utils.requestReturn({ data: "" })

  //拿到预付款金额
  function getPayAdvance(res) {
    let selectLesson = res.approvalContent.selectLesson
    for (let index = 0; index < selectLesson.length; index++) {
      const element = selectLesson[index];
      if (element.estimateSignUp == 1) return element.signUpPrice
    }
  }

  //订单金额为0，执行后续的逻辑
  async function setOrderAfterAction() {
    let { type } = await cloud.nw.db.findByWhereJson({
      dbName: "web-course",
      whereJson: { _id: res.curriculum_id },
    });
    let resp = await cloud.nw.db.findByWhereJson({
      dbName: "web-curriculum",
      whereJson: { _id: type[0] },
    });
    let status
    //查询该课程是否需要审核
    if (resp.hasOwnProperty("isExamine") && resp.isExamine == 1) {
      status = 1
    } else {
      status = 2  //报名成功
    }
    return status
  }
}

//意向客户导出
async function intendedCustomersExport() {
  let query = { ...data }
  delete query.year
  delete query.affiliation


  query = cloud.utils.extractValidKeys(query)

  //报名所属
  if (data.affiliation && data.affiliation.length) {
    query["approvalContent.model.affiliation"] = { $in: data.affiliation }
  }

  //订单状态
  if (cloud.utils.isNumber(data.status)) {
    query.status = data.status
  } else {
    query.status = { $in: [0, 6] }
  }

  //如果有时间筛选
  if (data.year) {
    const startOfYear = new Date(data.year, 0, 1).getTime(); // 该年份的开始时间戳
    const endOfYear = new Date(data.year, 11, 31, 23, 59, 59, 999).getTime(); // 该年份的结束时间戳
    query["_add_time"] = { $gt: startOfYear, $lt: endOfYear }
  }

  //如果有分类查询
  if (data.type) {
    let lastType = data.type[data.type.length - 1]
    const docs = await dbm.collection('web-course').find({ type: { $in: [lastType] } }).toArray()
    let arr = <any>[]
    if (docs && docs.length) {
      for (let index = 0; index < docs.length; index++) {
        const element = docs[index];
        arr.push(element._id)
      }
      delete query.type
    }
    if (data.curriculum_id) {
      if (arr.includes(data.curriculum_id)) {
        query["curriculum_id"] = data.curriculum_id
      } else {
        query["curriculum_id"] = { $in: [] }
      }
    } else {
      query["curriculum_id"] = { $in: arr }
    }
  }

  //模糊搜索
  let arr = ["out_trade_no"]
  arr.forEach(element => {
    if (data[element]) {
      query[element] = db.RegExp({  //模糊搜索
        regexp: data[element],
        options: 'i'
      })
    }
  });

  let info = await dbm.collection(dbName).find(query).toArray()
  return cloud.utils.requestReturn({ data: info })
}

//意向客户
async function intendedCustomers() {
  let query = { ...data }
  delete query.pageIndex
  delete query.pageSize
  delete query.year
  delete query.affiliation
  delete query.name
  delete query.enterprise

  query = cloud.utils.extractValidKeys(query)

  //所在企业名称
  if (data.enterprise) {
    let arr1 = await dbm.collection(dbName)
      .find({ "approvalContent.model.enterprise": { $regex: data.enterprise.toString(), $options: "i" } })
      .project({ _id: 1 }).toArray()

    let arr2 = await dbm.collection(dbName)
      .find({ "approvalContent.model.enterprise_department": { $regex: data.enterprise.toString(), $options: "i" } })
      .project({ _id: 1 }).toArray()

    let array = [...arr1, ...arr2]
    let list = []
    array.forEach(element => { list.push(element._id) });
    query["_id"] = { $in: list } //特定的订单id
  }

  if (data.name) {
    query["approvalContent.model.name"] = { $regex: data.name, $options: "i" }
  }

  //订单状态
  if (cloud.utils.isNumber(data.status)) {
    query.status = data.status
  } else {
    query.status = { $in: [0, 6] }
  }

  //如果有时间筛选
  if (data.year) {
    const startOfYear = new Date(data.year, 0, 1).getTime(); // 该年份的开始时间戳
    const endOfYear = new Date(data.year, 11, 31, 23, 59, 59, 999).getTime(); // 该年份的结束时间戳
    query["_add_time"] = { $gt: startOfYear, $lt: endOfYear }
  }

  //模糊搜索
  let arr = ["out_trade_no"]
  arr.forEach(element => {
    if (data[element]) {
      query[element] = { $regex: query[element], $options: "i" }
    }
  });

  console.log("意向订单的筛选", query)

  let res = await cloud.nw.db.selects({
    dbName,
    getCount: true,
    pageIndex: data.pageIndex,
    pageSize: data.pageSize,
    whereJson: query,
    sortArr: [{ "name": "_add_time", "type": "desc" }],
    foreignDB: [
      {
        dbName: "web-course",//副表 order
        localKey: "curriculum_id", //主表外键名
        foreignKey: "_id", //副表外键名
        as: "curriculum_Info", //副表连表结果的别名
        limit: 1,
        // 副表字段显示规则
        fieldJson: {
          name: true,
          invoiceStart: true,
          invoiceEnd: true,
          type: true,
        },
      },
    ]
  });
  return cloud.utils.requestReturn({ data: res })
}

async function clearAll() {
  await dbm.collection(dbName).deleteMany({})
  return cloud.utils.requestReturn({ data: "清空完成" })
}

async function details() {
  let res = await cloud.nw.db.findByWhereJson({
    dbName,
    whereJson: data,
  });
  await changeOrderInfo(data)
  return cloud.utils.requestReturn({ data: res })
}

async function add() {
  await cloud.nw.db.add({
    dbName,
    dataJson: data,
    cancelAddTime: true
  });
  return cloud.utils.requestReturn({ data: "" })
}

async function list() {
  let query = { ...data }
  delete query._id
  delete query.pageIndex
  delete query.pageSize
  delete query.year
  delete query.affiliation
  delete query.enterprise
  query = cloud.utils.fuzzyQuery(query)

  //未结束的订单 || 付款时间是传入年份的订单
  let withinScopeOrders = <any>[]

  //如果有时间筛选
  if (data.year) {
    //判断是否有挪至次年的标记，有的话是否等于传入的年份
    let aa = await dbm.collection(dbName).find({
      statisticsYear: {
        $exists: true,   // 判断属性存在[1,2](@ref)
        $eq: data.year        // 验证值等于2025[5](@ref)
      }
    }).project({ _id: 1 }).toArray()

    //没有标记，正常筛选
    let timeobj = {
      _add_time_str: { $regex: data.year.toString(), $options: "i" },
      statisticsYear: { $exists: false }
    }
    let bb = await dbm.collection(dbName).find(timeobj).project({ _id: 1 }).toArray()
    let cc = [...aa, ...bb]  //正常年份的订单和有延后的订单合并
    cc.forEach(element => {
      withinScopeOrders.push(element._id)
    });
    query["_id"] = { $in: withinScopeOrders } //特定的订单id
  }

  //报名所属
  if (data.affiliation && data.affiliation.length) {
    let array = await dbm.collection("admin-class-student").find({ affiliation: { $in: data.affiliation } })
      .project({ orderId: 1 }).toArray()
    let list = []
    array.forEach(element => { list.push(element.orderId) });
    withinScopeOrders = cloud.utils.getCommonElements2([...withinScopeOrders], list)
    query["_id"] = { $in: withinScopeOrders } //特定的订单id
  }

  //所在企业名称
  if (data.enterprise) {
    let arr1 = await dbm.collection(dbName)
      .find({ "approvalContent.model.enterprise": { $regex: data.enterprise.toString(), $options: "i" } })
      .project({ _id: 1 }).toArray()

    let arr2 = await dbm.collection(dbName)
      .find({ "approvalContent.model.enterprise_department": { $regex: data.enterprise.toString(), $options: "i" } })
      .project({ _id: 1 }).toArray()

    let array = [...arr1, ...arr2]
    let list = []
    array.forEach(element => { list.push(element._id) });
    withinScopeOrders = cloud.utils.getCommonElements2([...withinScopeOrders], list)
    query["_id"] = { $in: withinScopeOrders } //特定的订单id
  }

  let users = ['name', 'mobile', "identityCard", 'email', 'graduationMajor', "workYears"]
  let userWhereJson = {}
  users.forEach(element => {
    if (data.hasOwnProperty(element) && data[element]) {
      userWhereJson[element] = data[element]
      delete query[element]
    }
  });
  if (!cloud.utils.isEmptyObject(userWhereJson)) {
    userWhereJson = cloud.utils.fuzzyQuery(userWhereJson)
    query['approvalContent'] = {
      model: userWhereJson
    }
  }

  //如果是后端admin查询
  if (data.isAdmin && (data.isAdmin == 1)) {
    delete query['isAdmin']
    delete query.status //清除订单状态
    if (!data.status.length) {
      query.status = { $in: [1, 2, 3, 7, 8, 10] }
    } else if (data.status && data.status.length) {
      let statusList = [...data.status]
      //如果有报名成功的状态，则添加到10状态
      if (statusList.includes(2) && !statusList.includes(10)) statusList.push(10)
      query.status = { $in: statusList }
    }
  } else {
    //如果是前端查询，那就只查询自己的数据
    query['userId'] = userId
  }

  console.log("订单查询条件", query)

  let res = await cloud.nw.db.selects({
    dbName,
    getCount: true,
    pageIndex: data.pageIndex,
    pageSize: data.pageSize,
    whereJson: query,
    sortArr: [{ name: 'refundTimestamp', "type": "desc" }, { "name": "_add_time", "type": "desc" }],
    fieldJson: {
      orderUserInfo: false, exp_time: false, balance_pay_info: false,
      pay_discount_info: false,
      //pay_info: false
    },
    foreignDB: [
      {
        dbName: "web-course",//副表 order
        localKey: "curriculum_id", //主表外键名
        foreignKey: "_id", //副表外键名
        as: "curriculum_Info", //副表连表结果的别名
        limit: 1,
        // 副表字段显示规则
        fieldJson: {
          name: true,
          invoiceStart: true,
          invoiceEnd: true,
          type: true,
        },
      },
      {
        dbName: "invoicing",//副表 order
        localKey: "out_trade_no", //主表外键名
        foreignKey: "ddlsh", //副表外键名
        as: "invoicing_Info", //副表连表结果的别名
        limit: 1,
        // 副表字段显示规则
        fieldJson: {
          isInvoicing: true,
          _status: true,
          ycyy: true,
          add_time: true,
          status: true
        },
      },
      {
        dbName: "admin-class-student",//副表 order
        localKey: "_id", //主表外键名
        foreignKey: "orderId", //副表外键名
        as: "class_Info", //副表连表结果的别名
        sortArr: [{ "name": "_add_time", "type": "desc" }],
        limit: 1,
        fieldJson: { classId: true, affiliation: true, },
      },
    ]
  });
  return cloud.utils.requestReturn({ data: res })
}

async function delFunc() {
  let res = await cloud.nw.db.findByWhereJson({
    dbName,
    whereJson: { _id: data._id }
  });
  await cloud.nw.db.del({
    dbName,
    whereJson: { _id: data._id }
  });
  let query = cloud.utils.deepcopy(res)
  delete query._id
  query["deletedUser"] = userId//记录删除人
  await cloud.nw.db.add({
    dbName: "order-del-log",
    dataJson: query,
    cancelAddTime: false
  });
  return cloud.utils.requestReturn({ data: "" })
}

async function update() {
  let query = { ...data }
  delete query.orderId
  await cloud.nw.db.update({
    dbName,
    whereJson: { _id: data.orderId },
    dataJson: query
  });

  //如果涉及修改订单金额
  let res = await cloud.nw.db.findByWhereJson({
    dbName, whereJson: { _id: data.orderId },
  });

  //如果有预付款金额 && 预付款金额=0 && 订单状态=0
  if (data.hasOwnProperty("signUpPrice") && (data.signUpPrice == 0) && (res.status == 0)) {
    changeOrderStatus(data.orderId)
  } else if (data.hasOwnProperty("price") && res.status == 8) {
    //如果订单的总价=0
    if (data.price == 0) changeOrderStatus(data.orderId)
    let balancePayment = Number(res.price) - Number(res.signUpPrice);//需要支付的尾款
    if (balancePayment == 0) changeOrderStatus(data.orderId)
  } else if (data.hasOwnProperty("price") && (res.status == 0) && (data.price == 0)) {
    await changeOrderStatus(data.orderId)
  }

  let { out_trade_no } = await cloud.nw.db.findByWhereJson({
    dbName,
    whereJson: { _id: data.orderId },
  });
  //修改订单金额相关
  await changeOrderInfo({ _id: data.orderId })
  // 改变学生来源
  changeStudentSource(out_trade_no);
  //更新订单里面的个人信息
  setOrderBaseInfo(data.orderId)
  return cloud.utils.requestReturn({ data: "" })
}

async function Search() {
  let data = await dbm.collection(dbName).find({}).toArray()
  return cloud.utils.requestReturn({ data })
}
